package com.inspinia.upms.server.controller.ream;

import com.inspinia.auth.rpc.api.AuthService;
import com.inspinia.upms.common.model.user.UpmsUser;
import com.inspinia.upms.common.model.user.UpmsUserStatus;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;

/**
 * shiro安全验证框架
 */
public class SecurityRealm extends AuthorizingRealm {

    private static Logger log = LoggerFactory.getLogger(SecurityRealm.class);

    @Resource
    private AuthService authService;

    /**
     * 获取登陆用户的权限信息
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected SimpleAuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        if (principalCollection == null) {
            throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
        }
        UpmsUser userByPrincipal = authService.getUserByPrincipal(principalCollection);
        return authService.getAuthorizationInfo(userByPrincipal.getUserName(),userByPrincipal.getAppName());
    }

    /**
     * 对登陆用户进行验证，判断密码是否正确
     *
     * @param authenticationToken
     * @return
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) {

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        // 通过表单接收的用户名
        String loginName = token.getUsername();

        if (loginName == null || "".equals(loginName)) {
            throw new UnknownAccountException();
        }

        // 通过登录名称查询用户信息
        UpmsUser user = authService.findByUserName(loginName);

        if (user != null) {


            //判断用是否被被冻结
            UpmsUserStatus status = user.getStatus();
            switch (status) {
                case DISABLE:
                    //账户已经被冻结.
                    throw new LockedAccountException();
                case DELETED:
                    //账户已经被删除.
                    throw new UnknownAccountException();
                default:
            }
            return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
        }
        throw new UnknownAccountException();
    }
}